import Vue from 'vue'
import VueRouter from 'vue-router'

// 以下方式使用了路由的懒加载 

// import Login from '../components/Login'
const Login = () => import(/* webpackChunkName: "login_home_welcome" */ '../components/Login')
// import Home from '../components/Home'
const Home = () => import(/* webpackChunkName: "login_home_welcome" */ '../components/Home')
// import Welcome from '../pages/Welcome'
const Welcome = () => import(/* webpackChunkName: "login_home_welcome" */ '../pages/Welcome')

// import Users from '../pages/Users'
const Users = () => import(/* webpackChunkName: "users_rights_roles" */ '../pages/Users')
// import Rights from '../pages/Rights'
const Rights = () => import(/* webpackChunkName: "users_rights_roles" */ '../pages/Rights')
// import Roles from '../pages/Roles'
const Roles = () => import(/* webpackChunkName: "users_rights_roles" */ '../pages/Roles')

// import Categories from '../pages/Categories'
const Categories = () => import(/* webpackChunkName: "categories_params" */ '../pages/Categories')
// import Params from '../pages/Params'
const Params = () => import(/* webpackChunkName: "categories_params" */ '../pages/Params')

// import Goods from '../pages/Goods'
const Goods = () => import(/* webpackChunkName: "goods" */ '../pages/Goods')
// import AddGoods from '../pages/Goods/AddGoods'
const AddGoods = () => import(/* webpackChunkName: "goods" */ '../pages/Goods/AddGoods')

// import Order from '../pages/Order'
const Order = () => import(/* webpackChunkName: "order_report" */ '../pages/Order')
// import Report from '../pages/Report'
const Report = () => import(/* webpackChunkName: "order_report" */ '../pages/Report')

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/users',
        component: Users
      },
      {
        path: '/rights',
        component: Rights
      },
      {
        path: '/roles',
        component: Roles
      },
      {
        path: '/categories',
        component: Categories
      },
      {
        path: '/params',
        component: Params
      },
      {
        path: '/goods',
        component: Goods
      },
      {
        path: '/goods/add',
        component: AddGoods,
      },
      {
        path: '/orders',
        component: Order,
      },
      {
        path: '/reports',
        component: Report,
      }
      
    ]
  }
]

const router = new VueRouter({
  routes
})

/* 
  to: 将要访问的路径
  from：代表从哪个路径跳转而来
  next： 是一个函数，表示放行
*/
router.beforeEach((to, from, next) => {
  // 如果用户访问的使登录页面直接放行
  if (to.path === '/login') return next()
  const tokenStr = window.sessionStorage.getItem('token')
  // 如果没有token，就不给放行到其他页面，只能强制跳转到登录页面
  if (!tokenStr) return next('/login')
  // 如果有token就放行
  next()
})

export default router
